//
//  Fireworks.m
//  MyPopStar
//
//  Created by tarena on 16/1/13.
//  Copyright © 2016年 ssnb. All rights reserved.
//

#import "Fireworks.h"

@implementation Fireworks

-(instancetype)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        [self mInit];
    }
    return self;
}
-(void)mInit{
    self.emitterLayer.emitterPosition = CGPointMake(self.bounds.size.width/2.f, self.bounds.size.height/2.f);
    CGSize viewSize= self.layer.bounds.size;
    self.emitterLayer.emitterPosition = CGPointMake(viewSize.width / 2.f,viewSize.height/2);
    self.emitterLayer.emitterSize     = CGSizeMake(viewSize.width/2, 0);
    
    self.emitterLayer.emitterMode     = kCAEmitterLayerPoints;
    self.emitterLayer.emitterShape    = kCAEmitterLayerSphere;
    self.emitterLayer.renderMode      = kCAEmitterLayerAdditive;
//    self.emitterLayer.seed            = (arc4random()%100)+1;
//    self.emitterLayer.birthRate       = 1;
    
    
}
-(CAEmitterCell *)burst{
    CAEmitterCell* burst = [CAEmitterCell emitterCell];
    burst.name =@"firework";
    burst.birthRate			= 1.0;		// at the end of travel
    burst.velocity			= 0;
    burst.scale				= 1;
    burst.lifetime			= 0.3;
    return burst;
}

-(CAEmitterCell *)spark{
    CAEmitterCell* spark = [CAEmitterCell emitterCell];
    spark.name              = @"firework";
    spark.birthRate			= 100;
    spark.velocity			= 150;
    spark.velocityRange     = 50;
    spark.emissionRange		= 2* M_PI;	// 360 deg
    spark.yAcceleration		= 100;		// gravity
    spark.lifetime			= 2;
    
    spark.contents			= (id) [[UIImage imageNamed:self.fireImgName] CGImage];
    spark.scale             =0.4;
    spark.scaleSpeed		=-0.2;
    spark.alphaSpeed		=-0.25;
    spark.spin				= 2* M_PI;
    spark.spinRange			= 2* M_PI;
    return spark;
}

-(void)show{
//    CAEmitterCell* burst = [self burst];
    CAEmitterCell* spark = [self spark];
    
    self.emitterLayer.emitterCells	= [NSArray arrayWithObject:spark];
//    burst.emitterCells				= [NSArray arrayWithObject:spark];
    
    CABasicAnimation *heartsBurst = [CABasicAnimation animationWithKeyPath:@"emitterCells.firework.birthRate"];
    heartsBurst.fromValue		= [NSNumber numberWithFloat:15];
    heartsBurst.toValue			= [NSNumber numberWithFloat:0];
    heartsBurst.duration		= 0.5;
    heartsBurst.timingFunction	= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    heartsBurst.delegate=self;
    [self.emitterLayer addAnimation:heartsBurst forKey:@"heartsBurst"];
    
    
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
//    dispatch_queue_t queue =dispatch_queue_create("ssnb", 0);
//    dispatch_async(queue, ^{
//        [NSThread sleepForTimeInterval:2];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self hide];
//        });
//    });
    [self hide];
}
-(void)hide{
    [self removeFromSuperview];
}
mdealloc

@end
